package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1.kafka的链接配置信息
        Properties prop = new Properties();
        prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // 额外配置
        // ack配置，消息确认配置
        prop.put(ProducerConfig.ACKS_CONFIG, "all");
        // retries，重试次数，100ms未响应后重试
        prop.put(ProducerConfig.RETRIES_CONFIG, 10);
        // compression，压缩配置，数据量大使用！
        prop.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");

        // 2.创建kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(prop);

        // 3.发送消息
        // 第一个参数：topic|第二个参数：消息的key|第三个参数：消息的value
        ProducerRecord<String, String> kvProducerRecord = new ProducerRecord<String, String>("topic-first", "key", "chiori");
        // 同步消息发送，可能产生阻塞
        // RecordMetadata recordMetadata = producer.send(kvProducerRecord).get();
        // System.out.println(recordMetadata.offset());
        // 异步消息发送
        producer.send(kvProducerRecord, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) {
                    System.out.println("异常：" + e);
                }
                System.out.println(recordMetadata.offset());
            }
        });



        // 4.关闭相关通信|必须关闭，否则发送不成功
        producer.close();
    }
}
